<template>
    <div class="CreateIntegralGoods">
        <el-card class="CreateIntegralGoods-card">
            <el-page-header 
                :icon="ArrowLeft" 
                v-if="route.query.isEdit"
                @back="PageGoBack">
                <template #content>
                    <span class="header-title">修改商品</span>
                </template>
            </el-page-header>
            <el-form 
                ref="ruleFormRef"
                :model="goodsForm" 
                :rules="goodsRules"
                label-width="300px"
                status-icon>
                <el-form-item label="商品名称：" prop="name">
                    <el-input class="good-input" v-model="goodsForm.name" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="商品简介：" prop="introduction">
                    <el-input class="good-input" v-model="goodsForm.introduction" placeholder="请输入商品标题" />
                </el-form-item>
                <el-form-item label="商品详情介绍：" prop="detailsIntroduce">
                    <el-input
                        class="good-detailsIntroduce"
                        v-model="goodsForm.detailsIntroduce"
                        :autosize="{ minRows: 4, maxRows: 8 }"
                        type="textarea"
                        placeholder="请输入商品详情介绍"
                    />
                </el-form-item>
                <el-form-item label="商品所需积分：" prop="price">
                        <el-input-number
                            class="good-input" 
                            v-model="goodsForm.price"
                            controls-position="right"
                            :min="1"
                        />
                </el-form-item>
                <el-form-item label="商品标签：" prop="label">
                    <el-select 
                        class="good-select" 
                        v-model="goodsForm.label" 
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :max-collapse-tags="3"
                        clearable
                        placeholder="请选择商品标签"
                    >
                        <el-option
                            v-for="item in labelOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属菜单：" prop="menu">
                    <el-select 
                        class="good-select" 
                        v-model="goodsForm.menu" 
                        clearable 
                        placeholder="请选择所属菜单"
                    >
                        <el-option
                            v-for="item in menuOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品主图列表（多张）：">
                    <el-upload 
                        class="image-upload" 
                        v-model:file-list="goodsBannerFileList"
                        action="/api/tiequan/upload" 
                        list-type="picture-card" 
                        :auto-upload="true"
                        :on-success="GoodsBannerImagesSuccess"
                        :limit="10">
                        <el-icon><Plus /></el-icon>
                        <template #file="{ file }">
                        <div class="banner-image">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span
                                    class="el-upload-list__item-preview"
                                    @click="handlePictureCardPreview(file)"
                                >
                                    <el-icon :size="24"><zoom-in /></el-icon>
                                </span>
                                <span
                                    class="el-upload-list__item-delete"
                                    @click="GoodsBannerImageRemove(file)"
                                >
                                    <el-icon :size="24"><Delete /></el-icon>
                                </span>
                            </span>
                        </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品详情图列表（多张）：">
                    <el-upload 
                        class="image-upload" 
                        v-model:file-list="goodsDetailsFileList"
                        action="/api/tiequan/upload" 
                        list-type="picture-card" 
                        :auto-upload="true"
                        :on-success="GoodsDetailsImagesSuccess"
                        :limit="10">
                        <el-icon><Plus /></el-icon>
                        <template #file="{ file }">
                        <div class="banner-image">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span
                                    class="el-upload-list__item-preview"
                                    @click="handlePictureCardPreview(file)"
                                >
                                    <el-icon :size="24"><zoom-in /></el-icon>
                                </span>
                                <span
                                    class="el-upload-list__item-delete"
                                    @click="GoodsDetailsImageRemove(file)"
                                >
                                    <el-icon :size="24"><Delete /></el-icon>
                                </span>
                            </span>
                        </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item class="opera-form-item">
                    <el-button type="primary" size="large" @click="SaveConfig(ruleFormRef)">{{ route.query.isEdit ? '修改' : '创 建' }}</el-button>
                    <el-button size="large" @click="ResetConfig(ruleFormRef)">重 置</el-button>
                </el-form-item>
            </el-form>

        </el-card>
    </div>
</template>
    
<script setup>
import { ref,reactive, onMounted } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { ArrowLeft,Plus,Delete,ZoomIn  } from "@element-plus/icons";
import { CreateScoreGoodsReq, GetMenuList, GetTagList } from '../utils/api/index.js';
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref();
const goodsForm = reactive({ //商品
    name: '', // 名称
    introduction: '', // 简介
    detailsIntroduce: '', // 详情介绍
    price: '', // 价格
    label: [], // 标签
    menu: '', // 菜单
});
const goodsRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 3, max: 20, message: '名字长度限制为3到20字', trigger: 'blur' },
  ],
  introduction: [
    { 
        required: true, 
        message: '请输入简介', 
        trigger: 'blur' 
    },
  ],
  detailsIntroduce: [
    { 
        required: true, 
        message: '请输入详情介绍', 
        trigger: 'blur' 
    },
  ],
  price: [
        { 
            required: true, 
            message: '请输入所需积分' 
        },
        { 
            type: 'number', 
            message: '价格必须为数字' 
        }
  ],
  label: [ // 标签
    {
      required: true,
      message: '请选择商品标签',
      trigger: 'change',
    },
  ],
  menu: [ // 标签
    {
      required: true,
      message: '请选择所属菜单',
      trigger: 'change',
    },
  ],
})
const labelOptions = ref([]);
const menuOptions = ref([]);
const goodsBannerFileList = ref([]);
const goodsDetailsFileList = ref([]);
const eidtId = ref(''); // 编辑Id
const PageGoBack = () => {
    router.go(-1)
}
const GetConfig = async () => {
    if(route.query.isEdit) {
        let { 
            name,
            header,
            details,
            price,
            category_id,
            menu_id,
            bannerImgs,
            detailsImgs, 
            id
        } = JSON.parse(sessionStorage.editData);
        eidtId.value = id;
        goodsForm.name = name;
        goodsForm.introduction = header;
        goodsForm.detailsIntroduce = details;
        goodsForm.price = Number(price);
        goodsForm.label = category_id;
        goodsForm.menu = menu_id;
        goodsBannerFileList.value = bannerImgs.map((res) => {
            return {
                url: res
            }
        })
        goodsDetailsFileList.value = detailsImgs.map((res) => {
            return {
                url: res
            }
        })
    }
    let menuListRes = await GetMenuList({});
    if(menuListRes.code == 200) {
        menuOptions.value = menuListRes.data.list;
    }
    let tagListRes = await GetTagList({})
    if(tagListRes.code == 200) {
        labelOptions.value = tagListRes.data.list
    }
}
const GoodsBannerImagesSuccess = () => {
};
const GoodsBannerImageRemove = (file) => {
    let tarIdx = goodsBannerFileList.value.findIndex(res => res.uid == file.uid);
    goodsBannerFileList.value.splice(tarIdx,1);
};
const GoodsDetailsImagesSuccess = () => {
};
const GoodsDetailsImageRemove = (file) => {
    let tarIdx = goodsDetailsFileList.value.findIndex(res => res.uid == file.uid);
    goodsDetailsFileList.value.splice(tarIdx,1);
};
const SaveConfig = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(goodsBannerFileList.value.length == 0) {
                // eslint-disable-next-line no-undef
                ElMessage({
                    message: '请添加商品主图',
                    type: 'error',
                })
                return;
            }
            if(goodsDetailsFileList.value.length == 0) {
                // eslint-disable-next-line no-undef
                ElMessage({
                    message: '请添加商品详情图',
                    type: 'error',
                })
                return;
            }
            let bannerFileList = goodsBannerFileList.value.map((res) => {
                return res.response !=  undefined ? res.response.data.path : res.url;
            });
            let detailsFileList = goodsDetailsFileList.value.map((res) => {
                return res.response !=  undefined ? res.response.data.path : res.url;
            });
            CreateScoreGoodsReq({
                name: goodsForm.name,
                header: goodsForm.introduction,
                details: goodsForm.detailsIntroduce,
                price: goodsForm.price,
                category: goodsForm.label,
                menu: goodsForm.menu,
                bannerImgs: bannerFileList,
                detailsImgs: detailsFileList,
                id: route.query.isEdit ? eidtId.value : undefined
            }).then(res => {
                if(res.code == 200){
                    // eslint-disable-next-line no-undef
                    ElMessage({
                        showClose: true,
                        message: '保存成功',
                        type: 'success',
                    })
                    setTimeout(() => {
                        if(route.query.isEdit) {
                            router.go(-1)
                        } else {
                            router.push({
                                name: 'IntegralList',
                            });
                        }
                    },1000)
                };
            })
        } else {
            console.log('error submit!', fields)
        }
    })
  
};
const ResetConfig = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  goodsBannerFileList.value = [];
  goodsDetailsFileList.value = [];
}
onMounted(() => {
    GetConfig()
})
</script>
    
<style scoped lang="scss">
.CreateIntegralGoods{
    width: 100%;
    height: 100%;
    &-card{
        width: 100%;
        height: 100%;
        :deep .el-card__body{
            height: 100%;
            overflow-y: scroll;
            .header-title{
                color: #409EFF;
                font-weight: bold;
                // font-size: 24px;
            }
            .el-form{
                margin: 40px;
                .el-form-item{
                    margin-bottom: 25px;
                    .el-form-item__label{
                        font-weight: 600;
                        // font-size: 18px;
                    }
                    .good-input,.good-select{
                        width: 300px;
                        // height: 50px;
                    }
                    .good-detailsIntroduce{
                        width: 300px;
                    }
                    .el-form-item__error{
                        // font-size: 14px;
                        padding-top: 4px
                    }
                  
                    .image-upload{
                        .el-upload-list{
                            width: 100%;
                            height: 100%;
                            .el-upload{
                                width: 200px;
                                height: 200px;
                            }
                            .el-upload-list__item{
                                width: 200px;
                                height: 200px;
                            }
                        }
                    }
                }
            }
           
        }
    }
}
</style>